home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 901 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Alignment restrictions...
  5. Date: Wed, 10 Jan 96 00:02:17 GMT
  6. Organization: none
  7. Message-ID: <821232137snz@genesis.demon.co.uk>
  8. References: <DKxHxG.EK1@ridgecrest.ca.us>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <DKxHxG.EK1@ridgecrest.ca.us>
  15.            mcclung@owens.ridgecrest.ca.us "Scott McClung" writes:
  16.  
  17. ...
  18.  
  19. >I was porting some code out that had statements like:
  20. >
  21. >short value;  /* 16 bit value */
  22. >char *ptr;    /* 32 bit pointer, no alignment restrictions */
  23. >
  24. >value = *(short *)ptr;
  25. >
  26. >It worked on, say, Intel x86, or on values of ptr that happened to be
  27. >aligned (auto variables, in this case), but is not a general solution
  28. >on SPARC or other RISC architectures (MIPS and PA-RISC have similar
  29. >restrictions, if I recall.)  The pointer in question happened to be
  30. >into an mmap()'ed image file, so the alignment is not guaranteed.  Bus
  31. >errors.
  32. >
  33. >I replaced it with:
  34. >
  35. >value = *ptr << 8 | *(ptr + 1);
  36.  
  37. What are the byte order conventions in the 'image file'? What you have here
  38. assumes big endian while the code at the top just assumes the byte order
  39. is the same as the target variable. In the latter case this problem is
  40. easily solved by:
  41.  
  42.     memcpy(&value, ptr, sizeof value);
  43.  
  44. >Which works.  I'd just like to find out how this is generally dealt
  45. >with in code...  Actually, a magic compiler switch would be nice. :-)
  46. >(I'm working with gcc 2.7.2, BTW.)  I'll probably replace the
  47. >statement above with some inline function that checks the alignment of
  48. >ptr, and acts appropriately.  I guess I'm just looking for your
  49. >collective wisdom on this topic.
  50.  
  51. I suspect that the tailored inline code that a good compiler can generate
  52. for memcpy, especially with a fixed, small size would be difficult to beat.
  53.  
  54. -- 
  55. -----------------------------------------
  56. Lawrence Kirby | fred@genesis.demon.co.uk
  57. Wilts, England | 70734.126@compuserve.com
  58. -----------------------------------------
  59.